package DataStuctures.LinkList;

public class LinkList<E> {

    private class Node{
        public  E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e){
            this(e,null);
        }

        public Node(){
            this(null,null);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    private Node head;
    int size;


    public LinkList(){
        head = null;
        size = 0;
    }

    //返回链表中的元素个数
    public int getSize(){
        return size;
    }


    //返回链表是否为空
    public boolean isEmpty(){
        return size == 0;
    }

    //在链表表头添加新的元素
    public void addFirst(E e){
    /*
        Node node = new Node(e);
        node.next = head;
        head = node;
    */

        head = new Node(e,head);
        size++;
    }

    //在链表的index位置添加新的元素e
    public void add(int index,E e){

        if(index < 0 || index >size){
            throw new IllegalArgumentException("Add Failed,Illegal index");
        }
        if (index  == 0) {
            addFirst(e);
        }else {
            Node prev = head;
            //遍历prev 把prev指向要加入位置的前一个元素
            for (int i = 0; i < index-1; i++) {  //找的是插入位置的前一个元素，所以要-1
                prev = prev.next;   //一直向前移动，直到到了index-1的位置
            }
        /*
            Node node = new Node(e);
            node.next = prev.next;     //把新节点的下一节点指向prev原来的下一节点
            prev.next = node;            //原来下一节点指向为node
        */

            prev.next = new Node(e, prev.next);
            size++;
        }
    }

    public void addLast(E e){
        add(size,e);
    }
}
